package org.example.struct.array;

/**
 * @author liyishan
 * @date 2024/1/22 09:31
 * @apiNote
 */

public class Test00058LengthOfLastWord {
    public static void main(String[] args) {
        System.out.println(lengthOfLastWord("  fly me   to   the moon  "));
    }

    public static int lengthOfLastWord(String s) {
        int len = s.length();
        int lastLen = len;
        int firstLen = 0;
        // 从后往前遍历，找到第一个非空格
        for (int i = len - 1; i >= 0; i--) {
            if(s.charAt(i) != ' '){
                lastLen = i;
                break;
            }
        }
        for(int i = lastLen;i>=0;i--) {
            if(s.charAt(i) == ' '){
                firstLen = i+1;
                break;
            }
        }
        return lastLen-firstLen+1;
    }

    public static int lengthOfLastWord2(String s) {
        int size = s.length()-1;
        while(s.charAt(size) ==  ' '){
            size--;
        }
        int len = 0;
        while(size >= 0 && s.charAt(size) != ' '){
            len++;
            size--;
        }
        return len;
    }
}
